<template>
    <a-form class="basic-form" :labelCol="{ flex: '140px', class: 'title' }" :wrapperCol="{ class: 'content'}" :model="projOpt" ref="formRef" :rules="basicRules">
        <h1 id="basic">总体配置</h1>
        <a-flex class="conf-container" :gutter="8" vertical>
            <a-alert class="error" v-if="errors.length" type="error" showIcon :message="`保存时发生错误：`">
                <template #description>
                    <ul>
                        <li v-for="(v, k) in errors" :key="k">{{ v }}</li>
                    </ul>
                </template>
            </a-alert>
            <a-form-item class="option-item" label="申请年份" name="ApplyYear">
                <a-input v-model:value="projOpt.ApplyYear" show-count :maxlength="4"/>
                <template #help>
                    该值必须大于或等于{{ currentYear }}。学生使用申报功能后，项目“申请年份”字段自动设置为此值。同时，在大创项目的搜索框中，允许搜索的范围自动设置为 2014至配置值。
                </template>
            </a-form-item>
            <a-form-item class="option-item" label="申请批次" name="Batch">
                <a-input v-model:value="projOpt.Batch" show-count :maxlength="1"/>
                <template #help>
                    这个值只能设置为1或者2。学生使用申报功能后，项目“申请批次”字段自动设置为此值。
                </template>
            </a-form-item>
            <a-form-item class="option-item" label=" " :colon="false">
                <a-button type="primary" @click="submit" :loading="loading">提交</a-button>
            </a-form-item>
        </a-flex>
    </a-form>
</template>


<script setup>
import app from '@/app'
import { reactive, ref } from 'vue';
import projOpt, { saveOption } from '../ProjectOption'
import { message } from 'ant-design-vue';

const currentYear = (new Date()).getFullYear();
const basicRules = reactive({
    ApplyYear: [
        {
            type: "string", required: true,
            validator (rule, value, cb, source, options) {
                let { promise, resolve, reject} = app.withResolvers();
                let year = parseInt(value);
                if (isNaN(year)) reject("必须输入一个数字");
                else if (year < currentYear) reject(`申请年份必须大于或等于${currentYear}`);
                else resolve();
                return promise;
            }
        }
    ],
    Batch: { required: true, type: "enum", enum: ['1', '2'], message: "申请批次只能设置为1或者2" }
});

const formRef = ref();
const errors = ref([]);
const loading = ref(false);
async function submit () {
    loading.value = true;
    try {
        await formRef.value.validate();
        saveOption();
        message.success("保存成功");
    } catch {
        loading.value = false;
    } finally {
        loading.value = false;
    }
}
</script>../ProjectOption